'use client';

import React, { useState, useEffect } from 'react';
import { ProForm, ProFormText, ProFormTextArea, ProFormSelect, ProCard } from '@ant-design/pro-components';
import { Button, Space, Table, Tag, Popconfirm, message, Select } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { DemandOrder, DemandInstrumentOrder, OrderStatus } from '@/types/order';
import { ORDER_STATUS_TEXT, ORDER_STATUS_COLOR, PAYMENT_METHOD_OPTIONS } from '@/constants/order';

interface DemandOrderFormProps {
  mode: 'view' | 'edit' | 'create';
  initialData?: DemandOrder;
  onSave: (data: DemandOrder) => void;
  onCancel: () => void;
  currentUserRole?: string;
  currentUserId?: string;
}

const DemandOrderForm: React.FC<DemandOrderFormProps> = ({
  mode,
  initialData,
  onSave,
  onCancel,
  currentUserRole = 'admin',
  currentUserId = 'current_user',
}) => {
  const [form] = ProForm.useForm();
  const [loading, setLoading] = useState(false);
  const [demandOrder, setDemandOrder] = useState<DemandOrder | null>(initialData || null);
  const [availableInstruments, setAvailableInstruments] = useState<{
    id: string;
    name: string;
    category: string;
    price: number;
  }[]>([]);

  // 模拟可选仪器数据
  const mockAvailableInstruments = [
    { id: 'instrument004', name: '原子力显微镜', category: '微观形貌与结构表征', price: 500 },
    { id: 'instrument005', name: '红外光谱仪', category: '成分与结构分析', price: 300 },
    { id: 'instrument006', name: '热重分析仪', category: '物理性能表征', price: 400 },
  ];

  useEffect(() => {
    // 加载可选仪器
    setAvailableInstruments(mockAvailableInstruments);
    
    // 设置表单初始值
    if (initialData) {
      form.setFieldsValue({
        title: initialData.title,
        description: initialData.description,
        paymentMethod: initialData.paymentMethod,
      });
      setDemandOrder(initialData);
    }
  }, [initialData, form]);

  // 保存数据
  const handleSave = async (values: any) => {
    setLoading(true);
    try {
      let result: DemandOrder;
      
      if (mode === 'create') {
        // TODO: 调用创建API
        // const response = await orderApi.createDemandOrder({
        //   ...values,
        //   instrumentOrders: demandOrder?.instrumentOrders.map(item => ({
        //     instrumentId: item.instrumentId,
        //     notes: '',
        //   })) || [],
        // });
        // result = response.data;
        
        // 模拟创建结果
        result = {
          id: `demand_${Date.now()}`,
          orderNumber: `D${String(Date.now()).slice(-6)}`,
          userId: 'current_user_id',
          user: {} as any,
          ...values,
          instrumentOrders: demandOrder?.instrumentOrders || [],
          totalAmount: demandOrder?.instrumentOrders.reduce((sum, item) => sum + item.amount, 0) || 0,
          status: OrderStatus.PENDING_REVIEW,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        };
      } else {
        // TODO: 调用更新API
        // const response = await orderApi.updateDemandOrder(demandOrder!.id, values);
        // result = response.data;
        
        // 模拟更新结果
        result = {
          ...demandOrder!,
          ...values,
          updatedAt: new Date().toISOString(),
        };
      }
      
      message.success(`${mode === 'create' ? '创建' : '保存'}成功`);
      onSave(result);
    } catch (error) {
      console.error('保存失败:', error);
      message.error(`${mode === 'create' ? '创建' : '保存'}失败`);
    } finally {
      setLoading(false);
    }
  };

  // 添加仪器
  const [selectedInstrumentIds, setSelectedInstrumentIds] = useState<string[]>([]);

  const handleAddInstruments = () => {
    if (selectedInstrumentIds.length === 0) {
      message.warning('请先选择要添加的仪器');
      return;
    }

    const selectedInstruments = availableInstruments.filter(inst => 
      selectedInstrumentIds.includes(inst.id)
    );

    const newInstrumentOrders: DemandInstrumentOrder[] = selectedInstruments.map(inst => ({
      id: `inst_${Date.now()}_${Math.random()}`,
      instrumentId: inst.id,
      instrumentName: inst.name,
      instrumentCategory: inst.category,
      amount: inst.price,
      status: OrderStatus.PENDING_REVIEW,
      responsiblePerson: {
        id: 'default',
        name: '待分配',
        phone: '',
      },
    }));

    const updatedOrder = {
      ...demandOrder!,
      instrumentOrders: [...(demandOrder?.instrumentOrders || []), ...newInstrumentOrders],
      totalAmount: (demandOrder?.totalAmount || 0) + selectedInstruments.reduce((sum, inst) => sum + inst.price, 0),
    };

    setDemandOrder(updatedOrder);
    setSelectedInstrumentIds([]);
    message.success(`已添加 ${selectedInstruments.length} 个仪器`);
  };

  // 删除仪器
  const handleDeleteInstrument = (instrumentId: string) => {
    if (!demandOrder) return;

    const instrumentToDelete = demandOrder.instrumentOrders.find(item => item.id === instrumentId);
    if (!instrumentToDelete) return;

    const updatedOrder = {
      ...demandOrder,
      instrumentOrders: demandOrder.instrumentOrders.filter(item => item.id !== instrumentId),
      totalAmount: demandOrder.totalAmount - instrumentToDelete.amount,
    };

    setDemandOrder(updatedOrder);
    message.success('仪器已删除');
  };

  // 仪器列表表格列定义
  const instrumentColumns = [
    {
      title: '仪器名称',
      dataIndex: 'instrumentName',
      key: 'instrumentName',
      width: 200,
    },
    {
      title: '仪器分类',
      dataIndex: 'instrumentCategory',
      key: 'instrumentCategory',
      width: 180,
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (amount: number) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: OrderStatus) => (
        <Tag color={ORDER_STATUS_COLOR[status]}>
          {ORDER_STATUS_TEXT[status]}
        </Tag>
      ),
    },
    {
      title: '负责人',
      dataIndex: ['responsiblePerson', 'name'],
      key: 'responsiblePerson',
      width: 120,
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: DemandInstrumentOrder) => (
        <Space>
          {(mode === 'edit' || mode === 'create') && (
            <Popconfirm
              title="确定删除此仪器吗？"
              onConfirm={() => handleDeleteInstrument(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="link"
                danger
                size="small"
                icon={<DeleteOutlined />}
              >
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  const isReadonly = mode === 'view';
  const isEditing = mode === 'edit' || mode === 'create';

  return (
    <div>
      <ProCard title="基本信息" className="mb-6">
        <ProForm
          form={form}
          layout="horizontal"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          submitter={false}
          disabled={isReadonly}
          onFinish={handleSave}
        >
          <ProFormText
            name="title"
            label="需求名称"
            placeholder="请输入需求名称"
            rules={[{ required: true, message: '请输入需求名称' }]}
          />
          
          <ProFormTextArea
            name="description"
            label="需求描述"
            placeholder="请输入详细的需求描述"
            fieldProps={{ rows: 4 }}
            rules={[{ required: true, message: '请输入需求描述' }]}
          />
          
          <ProFormSelect
            name="paymentMethod"
            label="支付方式"
            options={PAYMENT_METHOD_OPTIONS}
            placeholder="请选择支付方式"
            rules={[{ required: true, message: '请选择支付方式' }]}
          />
        </ProForm>

        {demandOrder && (
          <div className="mt-4 grid grid-cols-2 gap-4 text-sm text-gray-600">
            <div>创建时间：{demandOrder.createdAt}</div>
            <div>更新时间：{demandOrder.updatedAt}</div>
            {demandOrder.user && (
              <div>创建用户：{demandOrder.user.realName} ({demandOrder.user.phone})</div>
            )}
            <div>总金额：<span className="text-lg font-semibold text-red-500">¥{demandOrder.totalAmount.toFixed(2)}</span></div>
          </div>
        )}
      </ProCard>

      <ProCard title="关联仪器" className="mb-6">
        {/* 添加仪器选择器 - 仅在编辑模式下显示 */}
        {isEditing && (
          <div className="mb-4 p-4 bg-gray-50 rounded">
            <div className="flex items-center gap-4">
              <span className="text-sm font-medium">选择仪器：</span>
              <Select
                mode="multiple"
                style={{ flex: 1, minWidth: 300 }}
                placeholder="请选择要添加的仪器"
                options={availableInstruments
                  .filter(inst => !demandOrder?.instrumentOrders.some(order => order.instrumentId === inst.id))
                  .map(inst => ({
                    label: `${inst.name} - ${inst.category} (¥${inst.price})`,
                    value: inst.id,
                  }))}
                value={selectedInstrumentIds}
                onChange={setSelectedInstrumentIds}
              />
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAddInstruments}
                disabled={selectedInstrumentIds.length === 0}
                style={{ backgroundColor: '#69cac3', borderColor: '#69cac3' }}
              >
                添加仪器
              </Button>
            </div>
          </div>
        )}

        <Table
          columns={instrumentColumns}
          dataSource={demandOrder?.instrumentOrders || []}
          rowKey="id"
          pagination={false}
          size="middle"
        />
      </ProCard>

      {/* 底部操作按钮 */}
      <div className="flex justify-center gap-4 py-6">
        <Button size="large" onClick={onCancel}>
          {isReadonly ? '返回' : '取消'}
        </Button>
        {!isReadonly && (
          <Button
            type="primary"
            size="large"
            loading={loading}
            onClick={() => form.submit()}
            style={{ backgroundColor: '#69cac3', borderColor: '#69cac3' }}
          >
            {mode === 'create' ? '创建' : '保存'}
          </Button>
        )}
      </div>
    </div>
  );
};



export default DemandOrderForm; 